package com.weme.common


import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Color
import android.graphics.Typeface
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.multidex.MultiDexApplication
import com.alibaba.android.arouter.launcher.ARouter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.mmkv.MMKV
import com.weme.common.service.WebSocketService
import com.weme.common.util.ExecutionTimeLogger
import com.weme.common.util.UtilsApp
import com.weme.common.view.MyClassicsFooter
import io.agora.chat.ChatClient
import io.agora.chat.ChatOptions
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.jessyan.autosize.AutoSizeConfig
import java.util.*


open class BaseApplication : MultiDexApplication() {


    companion object {
        lateinit var sInstance: BaseApplication

    }

    val viewModelProvider: ViewModelProvider by lazy {
        ViewModelProvider(ViewModelStore(), ViewModelProvider.AndroidViewModelFactory.getInstance(this))
    }
    override fun onCreate() {
        super.onCreate()
        if (getCurProcessName(this) == this.packageName) {
            ExecutionTimeLogger.start() // 开始计时
            sInstance = this
            UtilsApp.init(this)
            MMKV.initialize(this) //sp存储
            AutoSizeConfig.getInstance().setDesignWidthInDp(360).setDesignHeightInDp(800).isExcludeFontScale = true
            CoroutineScope(Dispatchers.Default).launch {
                initImsdk()
                CrashReport.initCrashReport(applicationContext, AppConfig.BUGLY_APPID, true)
                ARouter.init(this@BaseApplication)
                if (BuildConfig.DEBUG) {
                    ARouter.openLog()
                    ARouter.openDebug()
                }
                initSmartRefresh()
                setAppLanguageToSystemLanguage()
            }


            try {
                val intent = Intent(this, WebSocketService::class.java)
                startService(intent)
            } catch (_: java.lang.Exception) {

            }

        }
    }

    private fun initSmartRefresh() { //设置全局的Header构建器
        ClassicsHeader.REFRESH_HEADER_REFRESHING = getString(com.example.resources.R.string.header_refreshing) //"正在刷新...";
        ClassicsHeader.REFRESH_HEADER_LOADING = getString(com.example.resources.R.string.header_loading) //"正在加载...";
        ClassicsHeader.REFRESH_HEADER_RELEASE = getString(com.example.resources.R.string.header_release) //"释放立即刷新";
        ClassicsHeader.REFRESH_HEADER_FINISH = getString(com.example.resources.R.string.header_finish) //"刷新完成";
        ClassicsHeader.REFRESH_HEADER_FAILED = getString(com.example.resources.R.string.header_failed) //"刷新失败";
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            layout.setPrimaryColorsId(android.R.color.transparent, R.color.white) //全局设置主题颜色
            MaterialHeader(context).setSize(200).setColorSchemeColors(Color.parseColor("#FF03DAC5")) //.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
        }
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout -> //指定为经典Footer，默认是 BallPulseFooter
            layout.setPrimaryColorsId(android.R.color.transparent, R.color.white) //全局设置主题颜色
            MyClassicsFooter(context).setTextSizeTitle(13F).setDrawableSize(14f)
        }

    }

    private fun initImsdk() {
        ChatClient.getInstance().init(this, ChatOptions().apply { appKey = AppConfig.APP_KEY })
        ChatClient.getInstance().setDebugMode(BuildConfig.DEBUG)
        ChatClient.getInstance().logout(BuildConfig.DEBUG)

    }




    private fun setAppLanguageToSystemLanguage() {
        val systemLanguage = Locale.getDefault().language
        if (systemLanguage == "zh") return
        val languageToLoad = "en"
        val locale = Locale(languageToLoad)
        val config = Configuration()
        config.setLocale(locale)
        this.applicationContext.createConfigurationContext(config)
    }

    private fun getCurProcessName(context: Context): String {
        val pid = android.os.Process.myPid()
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (appProcess in activityManager.runningAppProcesses) {
            if (appProcess.pid == pid) {
                return appProcess.processName
            }
        }
        return ""
    }

}